package org.hamster.common.services
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.utils.ByteArray;
	
	import org.hamster.common.services.events.CacheEvent;
	import org.hamster.common.services.net.CacheLoader;
	import org.hamster.common.services.net.CacheURLLoader;

	public class ImageResourceCacheService extends RemoteResourceCacheService
	{
		public function ImageResourceCacheService()
		{
			super();
		}
		
		override protected function loadListCompleteHandler(event:Event):void
		{
			var urlLoader:CacheURLLoader = CacheURLLoader(event.currentTarget);
			urlLoaderListCleanListener(urlLoader);
			
			var loader:CacheLoader = new CacheLoader();
			loader.key = urlLoader.key;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgContentCompleteHandler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageContentErrorHandler);
			loader.loadBytes(urlLoader.data);
		}
		
		private function imgContentCompleteHandler(event:Event):void
		{
			var loaderInfo:LoaderInfo = LoaderInfo(event.currentTarget);
			loaderInfo.removeEventListener(Event.COMPLETE, imgContentCompleteHandler);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, imageContentErrorHandler);
			
			listCount--;
			putItem(CacheLoader(loaderInfo.loader).key, Bitmap(loaderInfo.content).bitmapData);
			if (listCount == 0 && this.hasEventListener(CacheEvent.ITEM_LIST_LOAD_ASYNC_COMPLETE)) {
				listCount = -1;
				var disEvt:CacheEvent = new CacheEvent(CacheEvent.ITEM_LIST_LOAD_ASYNC_COMPLETE);
				this.dispatchEvent(disEvt);
			}
		}
		
		private function imageContentErrorHandler(event:Event):void
		{
			var loaderInfo:LoaderInfo = LoaderInfo(event.currentTarget);
			loaderInfo.removeEventListener(Event.COMPLETE, imgContentCompleteHandler);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, imageContentErrorHandler);
			
			listCount--;
			if (listCount == 0 && this.hasEventListener(CacheEvent.ITEM_LIST_LOAD_ASYNC_COMPLETE)) {
				listCount = -1;
				var disEvt:CacheEvent = new CacheEvent(CacheEvent.ITEM_LIST_LOAD_ASYNC_COMPLETE);
				this.dispatchEvent(disEvt);
			}
		}
		
	}
}